package com.dandelion.api.controller;

import com.dandelion.api.manager.UserAddressManager;
import com.dandelion.api.request.UserAddressRequest;
import com.dandelion.common.domain.UserAddressVO;
import com.dandelion.common.http.HttpContext;
import com.rockit.core.pojo.JsonResult;
import com.rockit.core.pojo.Pagination;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/user/addr")
public class UserAddressController extends BaseRestController {
    @Autowired
    private UserAddressManager userAddressManager;

    @RequestMapping("/list")
    public JsonResult getUserAddressList(@Valid @ModelAttribute Pagination pagination, BindingResult bindingResult) {
        assertValid(bindingResult);
        long userId = HttpContext.current().getRequireUserId();
        List<UserAddressVO> addressList = userAddressManager.getUserAddressList(userId, pagination);
        return ok(addressList);
    }

    @RequestMapping("/add")
    public JsonResult addNewUserAddress(@Valid @ModelAttribute UserAddressRequest request,
                                        BindingResult bindingResult) {
        assertValid(bindingResult);
        userAddressManager.addNewUserAddress(HttpContext.current().getRequireUserId(), request);
        return ok();
    }

    @RequestMapping("/update")
    public JsonResult updateUserAddress(Long addressId,
                                        @Valid @ModelAttribute UserAddressRequest request,
                                        BindingResult bindingResult) {
        assertValid(bindingResult);
        Long userId = HttpContext.current().getRequireUserId();
        userAddressManager.updateUserAddress(userId, addressId, request);
        return ok();
    }

    @RequestMapping("/delete")
    public JsonResult deleteUserAddress(Long addressId) {
        Long userId = HttpContext.current().getRequireUserId();
        userAddressManager.deleteUserAddress(userId, addressId);
        return ok();
    }
}
